import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:yw_bapp/dao/common_dao.dart';
import 'package:yw_bapp/model/phone_code_model.dart';
import 'package:yw_bapp/model/phone_login_model.dart';
import 'package:yw_bapp/pages/store_select.dart';
import 'package:yw_bapp/provider/login_phone_provider.dart';
import 'package:yw_bapp/utils/loacl_storage.dart';
import 'package:yw_bapp/utils/show_tip_pop.dart';
import 'package:yw_bapp/widgets/circle_check_box.dart';
import 'package:yw_bapp/widgets/loading_pop_widget.dart';
import 'package:yw_bapp/widgets/m_btn.dart';
import 'package:yw_bapp/widgets/safe_area_bar_widget.dart';
import 'package:yw_bapp/widgets/show_toast.dart';

class InputCode extends StatefulWidget {
  final String title;
  final String phoneNum;

  const InputCode({Key key, @required this.title, @required this.phoneNum})
      : super(key: key);
  @override
  _InputCodeState createState() => _InputCodeState();
}

class _InputCodeState extends State<InputCode> {
  // 验证码控制器
  TextEditingController codeController = TextEditingController();
  // 下一步按钮的颜色
  bool isActive = false;
  // 按钮点击色
  Color btnActiveColor = ColorUtil.color('#FFC49226');
  // 按钮默认色
  Color btnDefaultColor = ColorUtil.color('#FFDDDDDD');
  // 文字点击色
  Color textActiveColor = Colors.white;
  // 文字默认色
  Color textDefaultColor = ColorUtil.color("#FFAFAFAF");
  // 错误提示的展示
  bool error = false;
  // 协议勾选
  bool agree = false;
  // 验证码倒计时
  Timer _timer;
  int _countdownTime = 0;
  // 验证码已发送
  bool sendSuccess;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _countdownTime = 15;
    sendSuccess = true;
    // 开始倒计时
    startCountdownTimer();
  }

  @override
  void dispose() {
    if (_timer != null) {
      _timer.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final phone = context.watch<LoginPhoneProvider>().loginPhone;
    return Scaffold(
      appBar: XAppBar(
        statusBarColor: ColorUtil.color("#FFC49226"),
        bgColor: ColorUtil.color('#FFC49226'),
        title: "",
        iconColor: Colors.white,
      ),
      body: Container(
        padding: EdgeInsets.fromLTRB(25, 49.5, 25, 0),
        decoration: BoxDecoration(color: Colors.white),
        child: Column(
          children: <Widget>[
            // 标题
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Text(
                  "验证码已发送至",
                  textAlign: TextAlign.start,
                  style: TextStyle(
                      color: ColorUtil.color("#FF333333"),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      decoration: TextDecoration.none),
                ),
              ],
            ),
            // 副标题
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  // 文字
                  Row(
                    children: <Widget>[
                      Text(
                        "手机号",
                        style: TextStyle(
                            color: ColorUtil.color("#FF9A9A9A"), fontSize: 15),
                      ),
                      Text("$phone",
                          // "${widget.phoneNum}",
                          style: TextStyle(
                              color: ColorUtil.color("#FFFF7200"),
                              fontSize: 15)),
                      Text(",请查收",
                          style: TextStyle(
                              color: ColorUtil.color("#FF9A9A9A"),
                              fontSize: 15)),
                      Text(sendSuccess ? "(${_countdownTime}s)" : "")
                    ],
                  ),
                  GestureDetector(
                    child: Text("重新获取",
                        style: TextStyle(
                            color: ColorUtil.color("#FFFF7200"), fontSize: 15)),
                    onTap: () {
                      setState(() {
                        _countdownTime = 15;
                        sendSuccess = true;
                        // 请求接口发送验证码
                        _getCode(context);
                      });
                    },
                  )
                ],
              ),
            ),
            // 输入框
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: Padding(
                      padding: EdgeInsets.fromLTRB(0, 35, 0, 40),
                      child: Material(
                        child: TextField(
                            controller: codeController,
                            keyboardType: TextInputType.number,
                            maxLength: 6,
                            autofocus: false,
                            decoration: InputDecoration(
                                contentPadding: EdgeInsets.all(10),
                                hintText: "请输入6位短信验证码",
                                helperText: error ? "*短信验证码错误" : "",
                                helperStyle: TextStyle(
                                    color: ColorUtil.color("#FFFF0000"),
                                    fontSize: 12),
                                focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(
                                  color: Colors.grey,
                                )),
                                hintStyle: TextStyle(
                                    color: ColorUtil.color("#FF999999"),
                                    fontSize: 15)),
                            onChanged: _textFieldChanged),
                      ),
                    )),
                // 清除按钮
                Material(
                  child: codeController.text != ''
                      ? IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            setState(() {
                              codeController.text = '';
                              isActive = false;
                              error = false;
                            });
                          },
                        )
                      : null,
                )
              ],
            ),
            //  协议勾选
            Row(
              children: <Widget>[
                // 勾选
                RoundCheckBox(
                  value: agree,
                  activeColor: ColorUtil.color("#FFFF7200"),
                  onChanged: (bool val) {
                    setState(() {
                      agree = !agree;
                      isActive = agree ? true : false;
                    });
                  },
                ),
                // 协议
                LimitedBox(
                  maxWidth: 290,
                  child: Text("我已阅读并同意《有味商家版用户协议》，《有味商家版隐私政策》",
                      maxLines: 2,
                      style: TextStyle(
                          color: ColorUtil.color("#FFFF7200"), fontSize: 12)),
                ),
              ],
            ),
            // 按钮
            Container(
              margin: EdgeInsets.only(top: 20),
              child: MBtn(
                function: () {
                  _login(context);
                },
                title: '${widget.title}',
                btnWidth: 325,
                btnHeight: 47,
                borderRadius: 5,
                hasBg: true,
                textColor: isActive ? textActiveColor : textDefaultColor,
                bgColor: isActive ? btnActiveColor : btnDefaultColor,
                borderColor: isActive ? btnActiveColor : btnDefaultColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 输入框改变的回调
  void _textFieldChanged(String value) {
    if (value.length < 6 || !agree) {
      setState(() {
        isActive = false;
      });
    } else {
      setState(() {
        isActive = true;
      });
    }
  }

  // 点击按钮下一步，发送验证码,并开启倒计时
  void _getCode(BuildContext context) {
    // 加载弹窗
    showLoadingDialog(context);
    // 请求接口数据
    CommonDao.GetCode(widget.phoneNum).then((PhoneCodeModel model) => {
          // 关闭弹窗
          Navigator.pop(context),
          if (model.status == 200)
            {
              ShowToast.toast(context,
                  msg: "验证码发送成功", position: ToastPostion.center),
              // 开始倒计时
              startCountdownTimer()
            }
          else
            {
              ShowToast.toast(context,
                  msg: model.msg, position: ToastPostion.center)
            }
        });
  }

  // 开始验证码倒计时
  void startCountdownTimer() {
    const oneSec = const Duration(seconds: 1);
    var callback = (timer) => {
          setState(() {
            if (_countdownTime < 1) {
              sendSuccess = false;
              _timer.cancel();
            } else {
              _countdownTime = _countdownTime - 1;
            }
          })
        };
    _timer = Timer.periodic(oneSec, callback);
  }

  // 点击登录，登录成功并跳转页面
  void _login(BuildContext context) {
    // 加载弹窗
    showLoadingDialog(context);
    // 请求接口数据
    CommonDao.ToLogin(widget.phoneNum, codeController.text)
        .then((PhoneLoginModel model) => {
              // 关闭弹窗
              Navigator.pop(context),
              if (model.status == 200)
                {
                  ShowToast.toast(context,
                      msg: "登录成功", position: ToastPostion.center),
                  // 将ID存成Token
                  setStorage('Token', model.data.iD.toString()),
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => StoreSelect())),
                  LoadingPop.show(context)
                }
              else
                {
                  ShowToast.toast(context,
                      msg: model.error, position: ToastPostion.center),
                }
            });
  }
}
